Compiled from Original Code by:
# To support both python 2 and python 3
from __future__ import division, print_function, unicode_literals
# Common imports
import numpy as np
import os
import pandas as pd
# to make this notebook's output stable across runs
np.random.seed(42)
# To plot pretty figures
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
plt.rcParams['axes.labelsize'] = 14
plt.rcParams['xtick.labelsize'] = 12
plt.rcParams['ytick.labelsize'] = 12
# Where to save the figures
PROJECT_ROOT_DIR = "."
CHAPTER_ID = "unsupervised_learning"
def save_fig(fig_id, tight_layout=True):
path = os.path.join(PROJECT_ROOT_DIR, "images", CHAPTER_ID, fig_id + ".png")
print("Saving figure", fig_id)
if tight_layout:
plt.tight_layout()
plt.savefig(path, format='png', dpi=300)
# Ignore useless warnings (see SciPy issue #5998)
import warnings
warnings.filterwarnings(action="ignore", module="scipy", message="^internal gelsd")
import glob, os
def rename(dir, pattern, titlePattern):
for pathAndFilename in glob.iglob(os.path.join(dir, pattern)):
title, ext = os.path.splitext(os.path.basename(pathAndFilename))
os.rename(pathAndFilename,
os.path.join(dir, titlePattern % title + ext))
from PIL import Image
# We need to rename our labelled and bucketed image files sequentially so that the below code can associate a label
# with an image
# Comment Out as required.
#To Do: Code for Looping through
#%%capture
#dir = '/Users/anthonysutton/ml2/image_similar/TSNE2_Reboot/TSNE_BUILDING_TYPE/FLAT/'
#dir = '/Users/anthonysutton/ml2/image_similar/TSNE2_Reboot/TSNE_BUILDING_TYPE/HOUSE/'
#dir = '/Users/anthonysutton/ml2/image_similar/TSNE2_Reboot/TSNE_BUILDING_TYPE/INDUSTRIAL/'
dir = '/Users/anthonysutton/ml2/image_similar/TSNE2_Reboot/TSNE_BUILDING_TYPE/RETAIL'
#Flats
#count = 0
#House
#count = 102
#Industrial
#count = 203
#Retail
count = 263
titlePattern = 'new(%s)'
pattern = '*.jpg'
for pathAndFilename in glob.iglob(os.path.join(dir, pattern)):
title, ext = os.path.splitext(os.path.basename(pathAndFilename))
#print(pathAndFilename, os.path.join(dir, titlePattern % title + ext))
print(pathAndFilename, os.path.join(dir, str(count) + ext))
os.rename(pathAndFilename, os.path.join(dir, str(count) + ext))
count = count + 1
# For now we will Copy over the files Manually. To Do: OS Util Loop
# Location = /Users/anthonysutton/ml2/image_similar/TSNE2_Reboot/Buildings
# Using Duhaimes modified Tensorflow Scripts:
# Instead of asking the last (softmax) layer of the neural network(Inception) for the text classifications of input
# images, we ask the penultimate layer of the neural network for the internal model weights for a given image,
# and store those weights as a vector representation of the input image.
# This will allow us to perform traditional vector analysis using images.
# Throws an error in Jupyter Kernal, sometimes need to run on command line
#%run -i /Users/anthonysutton/ml2/image_similar/classify_imagesDH.py \
# "/Users/anthonysutton/ml2/image_similar/TSNE2_Reboot/Buildings/*"
#Code By Douglas Duhaime - Yale DH Lab
from __future__ import absolute_import, division, print_function
"""
This is a modification of the classify_images.py
script in Tensorflow. The original script produces
string labels for input images (e.g. you input a picture
of a cat and the script returns the string "cat"); this
modification reads in a directory of images and
generates a vector representation of the image using
the penultimate layer of neural network weights.
Usage: python classify_images.py "../image_dir/*.jpg"
"""
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Simple image classification with Inception.
Run image classification with Inception trained on ImageNet 2012 Challenge data
set.
This program creates a graph from a saved GraphDef protocol buffer,
and runs inference on an input JPEG image. It outputs human readable
strings of the top 5 predictions along with their probabilities.
Change the --image_file argument to any jpg image to compute a
classification of that image.
Please see the tutorial and website for a detailed description of how
to use this script to perform image recognition.
https://tensorflow.org/tutorials/image_recognition/
"""
import os.path
import re
import sys
import tarfile
import glob
import json
import psutil
from collections import defaultdict
import numpy as np
from six.moves import urllib
import tensorflow as tf
FLAGS = tf.app.flags.FLAGS
# classify_image_graph_def.pb:
# Binary representation of the GraphDef protocol buffer.
# imagenet_synset_to_human_label_map.txt:
# Map from synset ID to a human readable string.
# imagenet_2012_challenge_label_map_proto.pbtxt:
# Text representation of a protocol buffer mapping a label to synset ID.
tf.app.flags.DEFINE_string(
'model_dir', '/tmp/imagenet',
"""Path to classify_image_graph_def.pb, """
"""imagenet_synset_to_human_label_map.txt, and """
"""imagenet_2012_challenge_label_map_proto.pbtxt.""")
tf.app.flags.DEFINE_string('image_file', '',
"""Absolute path to image file.""")
tf.app.flags.DEFINE_integer('num_top_predictions', 5,
"""Display this many predictions.""")
# pylint: disable=line-too-long
DATA_URL = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz'
# pylint: enable=line-too-long
class NodeLookup(object):
"""Converts integer node ID's to human readable labels."""
def __init__(self,
label_lookup_path=None,
uid_lookup_path=None):
if not label_lookup_path:
label_lookup_path = os.path.join(
FLAGS.model_dir, 'imagenet_2012_challenge_label_map_proto.pbtxt')
if not uid_lookup_path:
uid_lookup_path = os.path.join(
FLAGS.model_dir, 'imagenet_synset_to_human_label_map.txt')
self.node_lookup = self.load(label_lookup_path, uid_lookup_path)
def load(self, label_lookup_path, uid_lookup_path):
"""Loads a human readable English name for each softmax node.
Args:
label_lookup_path: string UID to integer node ID.
uid_lookup_path: string UID to human-readable string.
Returns:
dict from integer node ID to human-readable string.
"""
if not tf.gfile.Exists(uid_lookup_path):
tf.logging.fatal('File does not exist %s', uid_lookup_path)
if not tf.gfile.Exists(label_lookup_path):
tf.logging.fatal('File does not exist %s', label_lookup_path)
# Loads mapping from string UID to human-readable string
proto_as_ascii_lines = tf.gfile.GFile(uid_lookup_path).readlines()
uid_to_human = {}
p = re.compile(r'[n\d]*[ \S,]*')
for line in proto_as_ascii_lines:
parsed_items = p.findall(line)
uid = parsed_items[0]
human_string = parsed_items[2]
uid_to_human[uid] = human_string
# Loads mapping from string UID to integer node ID.
node_id_to_uid = {}
proto_as_ascii = tf.gfile.GFile(label_lookup_path).readlines()
for line in proto_as_ascii:
if line.startswith(' target_class:'):
target_class = int(line.split(': ')[1])
if line.startswith(' target_class_string:'):
target_class_string = line.split(': ')[1]
node_id_to_uid[target_class] = target_class_string[1:-2]
# Loads the final mapping of integer node ID to human-readable string
node_id_to_name = {}
for key, val in node_id_to_uid.items():
if val not in uid_to_human:
tf.logging.fatal('Failed to locate: %s', val)
name = uid_to_human[val]
node_id_to_name[key] = name
return node_id_to_name
def id_to_string(self, node_id):
if node_id not in self.node_lookup:
return ''
return self.node_lookup[node_id]
def create_graph():
"""Creates a graph from saved GraphDef file and returns a saver."""
# Creates graph from saved graph_def.pb.
with tf.gfile.FastGFile(os.path.join(
FLAGS.model_dir, 'classify_image_graph_def.pb'), 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
_ = tf.import_graph_def(graph_def, name='')
def run_inference_on_images(image_list, output_dir):
"""Runs inference on an image list.
Args:
image_list: a list of images.
output_dir: the directory in which image vectors will be saved
Returns:
image_to_labels: a dictionary with image file keys and predicted
text label values
"""
image_to_labels = defaultdict(list)
create_graph()
with tf.Session() as sess:
# Some useful tensors:
# 'softmax:0': A tensor containing the normalized prediction across
# 1000 labels.
# 'pool_3:0': A tensor containing the next-to-last layer containing 2048
# float description of the image.
# 'DecodeJpeg/contents:0': A tensor containing a string providing JPEG
# encoding of the image.
# Runs the softmax tensor by feeding the image_data as input to the graph.
softmax_tensor = sess.graph.get_tensor_by_name('softmax:0')
for image_index, image in enumerate(image_list):
try:
print("parsing", image_index, image, "\n")
if not tf.gfile.Exists(image):
tf.logging.fatal('File does not exist %s', image)
with tf.gfile.FastGFile(image, 'rb') as f:
image_data = f.read()
predictions = sess.run(softmax_tensor,
{'DecodeJpeg/contents:0': image_data})
predictions = np.squeeze(predictions)
###
# Get penultimate layer weights
###
feature_tensor = sess.graph.get_tensor_by_name('pool_3:0')
feature_set = sess.run(feature_tensor,
{'DecodeJpeg/contents:0': image_data})
feature_vector = np.squeeze(feature_set)
outfile_name = os.path.basename(image) + ".npz"
out_path = os.path.join(output_dir, outfile_name)
np.savetxt(out_path, feature_vector, delimiter=',')
# Creates node ID --> English string lookup.
node_lookup = NodeLookup()
top_k = predictions.argsort()[-FLAGS.num_top_predictions:][::-1]
for node_id in top_k:
human_string = node_lookup.id_to_string(node_id)
score = predictions[node_id]
print("results for", image)
print('%s (score = %.5f)' % (human_string, score))
print("\n")
image_to_labels[image].append(
{
"labels": human_string,
"score": str(score)
}
)
# close the open file handlers
proc = psutil.Process()
open_files = proc.open_files()
for open_file in open_files:
file_handler = getattr(open_file, "fd")
os.close(file_handler)
except:
print('could not process image index',image_index,'image', image)
return image_to_labels
def maybe_download_and_extract():
"""Download and extract model tar file."""
dest_directory = FLAGS.model_dir
if not os.path.exists(dest_directory):
os.makedirs(dest_directory)
filename = DATA_URL.split('/')[-1]
filepath = os.path.join(dest_directory, filename)
if not os.path.exists(filepath):
def _progress(count, block_size, total_size):
sys.stdout.write('\r>> Downloading %s %.1f%%' % (
filename, float(count * block_size) / float(total_size) * 100.0))
sys.stdout.flush()
filepath, _ = urllib.request.urlretrieve(DATA_URL, filepath, _progress)
print()
statinfo = os.stat(filepath)
print('Succesfully downloaded', filename, statinfo.st_size, 'bytes.')
tarfile.open(filepath, 'r:gz').extractall(dest_directory)
def main(_):
print("TEST")
maybe_download_and_extract()
if len(sys.argv) < 2:
print("please provide a glob path to one or more images, e.g.")
print("python classify_image_modified.py '../cats/*.jpg'")
sys.exit()
else:
output_dir = "Building_Vectors"
if not os.path.exists(output_dir):
os.makedirs(output_dir)
images = glob.glob(sys.argv[1])
image_to_labels = run_inference_on_images(images, output_dir)
with open("image_to_labels.json", "w") as img_to_labels_out:
json.dump(image_to_labels, img_to_labels_out)
print("all done")
if __name__ == '__main__':
tf.app.run()
# See what files have been created
import os
rootdir = '/Users/anthonysutton/ml2/image_similar/TSNE2_Reboot/Building_Vectors'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
print(os.path.join(subdir, file))
# To Do: OS Utils Code
# For Now Use Excel, Create File In Folowing Format
#labels = [1,1,1,2,2,2,3,3,3,4,4,4]
# FileName = /Users/anthonysutton/ml2/image_similar/TSNE2_Reboot/TSNE_Building_Type_Labels.txt
#Load CNN Vectors(npz) into Array
from sklearn.manifold import TSNE
import numpy as np
import glob, json, os
# create containers
vector_files = []
image_vectors = []
chart_data = []
maximum_imgs = 1000
# build a list of image vectors
vector_files = glob.glob('/Users/anthonysutton/ml2/image_similar/TSNE2_Reboot/Building_Vectors/*.npz')[:maximum_imgs]
#Ageron Method:
#print(vector_files)
for c, i in enumerate(vector_files):
image_vectors.append(np.loadtxt(i))
print(' * loaded', c, 'of', len(vector_files), 'image vectors')
image_vectors_check = np.asarray(image_vectors)
print(image_vectors_check.shape)
# build the tsne model on the image vectors
print('building tsne model')
#Duhaime Method:
#model = TSNE(n_components=2, random_state=0)
#np.set_printoptions(suppress=True)
#fit_model = model.fit_transform( np.array(image_vectors) )
# store the coordinates of each image in the chart data
#for c, i in enumerate(fit_model):
# image_name = os.path.basename(vector_files[c]).replace('.npz', '')
# chart_data.append({
# 'image': os.path.join('images', image_name),
# 'x': i[0],
# 'y': i[1]
# })
#with open('image_tsne_projections.json', 'w') as out:
# json.dump(chart_data, out)
#Model Fit:
tsne = TSNE(n_components=2, random_state=42)
X_reduced = tsne.fit_transform(image_vectors_check)
tsne_label_prop_type = np.loadtxt('/Users/anthonysutton/ml2/image_similar/TSNE2_Reboot/TSNE_Building_Type_Labels.txt')
tsne_label_prop_type.shape
labels = tsne_label_prop_type
len(labels)
from io import StringIO
file = open('/Users/anthonysutton/ml2/image_similar/TSNE2_Reboot/TSNE_Building_Type_Labels.txt', 'r')
#labels_in = np.genfromtxt(file, dtype='str')
labels_in = np.loadtxt(file)
#label_name_string = StringIO( labels_in +"\n")
#label_name_string
# StringIO behaves like a file object
#c = StringIO("0 1\n2 3")
#np.loadtxt(c)
y = labels_in
y.shape
# Recap: X=reduced Values and Y= labels
plt.figure(figsize=(13,10))
plt.scatter(X_reduced[:, 0], X_reduced[:, 1], c=y, cmap="jet")
plt.axis('off')
plt.colorbar()
plt.show()
# Focus on the Weaker Clusters
plt.figure(figsize=(9,9))
cmap = matplotlib.cm.get_cmap("jet")
for digit in (1, 2, 3):
plt.scatter(X_reduced[y == digit, 0], X_reduced[y == digit, 1], c=cmap(digit / 9))
plt.axis('off')
plt.show()
# Attempt to Clean Up Weaker Clusters(2, 3 = House and Industrial) with TSNE
idx = (y == 1) | (y == 2) | (y == 3)
X_subset =image_vectors_check[idx]
y_subset = y[idx]
tsne_subset = TSNE(n_components=2, random_state=42)
X_subset_reduced = tsne_subset.fit_transform(X_subset)
plt.figure(figsize=(9,9))
for digit in (1, 2, 3):
plt.scatter(X_subset_reduced[y_subset == digit, 0], X_subset_reduced[y_subset == digit, 1], c=cmap(digit / 9))
plt.axis('off')
plt.show()
from sklearn.preprocessing import MinMaxScaler
from matplotlib.offsetbox import AnnotationBbox, OffsetImage
def plot_digits(X, y, min_distance=0.05, images=None, figsize=(13, 10)):
# Let's scale the input features so that they range from 0 to 1
X_normalized = MinMaxScaler().fit_transform(X)
# Now we create the list of coordinates of the digits plotted so far.
# We pretend that one is already plotted far away at the start, to
# avoid `if` statements in the loop below
neighbors = np.array([[10., 10.]])
# The rest should be self-explanatory
plt.figure(figsize=figsize)
cmap = matplotlib.cm.get_cmap("jet")
digits = np.unique(y)
for digit in digits:
plt.scatter(X_normalized[y == digit, 0], X_normalized[y == digit, 1], c=cmap(digit / 9))
plt.axis("off")
ax = plt.gcf().gca() # get current axes in current figure
for index, image_coord in enumerate(X_normalized):
closest_distance = np.linalg.norm(np.array(neighbors) - image_coord, axis=1).min()
if closest_distance > min_distance:
neighbors = np.r_[neighbors, [image_coord]]
if images is None:
plt.text(image_coord[0], image_coord[1], str(int(y[index])),
color=cmap(y[index] / 9), fontdict={"weight": "bold", "size": 16})
else:
#image = images[index].reshape(359, 28, 28, 3)
image = images[index]
imagebox = AnnotationBbox(OffsetImage(image, cmap="binary"), image_coord)
ax.add_artist(imagebox)
X_reduced.shape
plot_digits(X_reduced, y)
plot_digits(X_subset_reduced, y_subset)
# Warning: Folder Cleaner
for infile in glob.glob("/Users/anthonysutton/ml2/image_similar/TSNE2_Reboot/Buildings/*.thumbnail.jpg"):
os.remove(infile)
#img = Image.open('/Users/anthonysutton/ml2/image_similar/LABEL_RUN_2_2_SAFE/FLAT/col_id_4702.jpg')
#img.thumbnail((64, 64), Image.ANTIALIAS) # resizes image in-place
#imgplot = plt.imshow(img)
size = 128, 128
for infile in glob.glob("/Users/anthonysutton/ml2/image_similar/TSNE2_Reboot/Buildings/*.jpg"):
file, ext = os.path.splitext(infile)
im = Image.open(infile)
im.thumbnail(size)
im.save(file + ".thumbnail.jpg", "JPEG")
#os.remove(infile)
#import glob
#import numpy as np
X_data = []
files = glob.glob ("/Users/anthonysutton/ml2/image_similar/TSNE2_Reboot/Buildings/*.thumbnail.jpg")
for myFile in files:
#print(myFile)
#image = cv2.imread (myFile)
#img = Image.open(myFile)
#imgplot = plt.imshow(img)
#img_in = Image.open(myFile)
#img_out = img_in.resize((120,120))
#img = np.array(img_out)
img = np.array(Image.open(myFile))
#img.shape
#img.rotate(45)
#img.resize((128,128))
print(img.shape)
X_data.append (img)
img_np = np.array(X_data)
#img.shape
#img_np.shape
#image_test = img_np.reshape(359, 28, 28, 3)
#image_test.shape
#for index in enumerate(img_np):
# print(img_np[index].shape)
# Image.resize(size, resample=0)
imgplot = plt.imshow(img_np[3])
print(img_np.shape)
#pil_im.resize((128,128))
plot_digits(X_reduced, y, images=img_np, figsize=(35, 25))
plot_digits(X_reduced, y, images=img_np, figsize=(22, 22))
plot_digits(X_subset_reduced, y_subset, images=img_np, figsize=(22, 22))
from sklearn.decomposition import PCA
import time
#X_reduced = tsne.fit_transform(image_vectors_check)
t0 = time.time()
X_pca_reduced = PCA(n_components=2, random_state=42).fit_transform(image_vectors_check)
t1 = time.time()
print("PCA took {:.1f}s.".format(t1 - t0))
plot_digits(X_pca_reduced, y)
plt.show()
from sklearn.manifold import LocallyLinearEmbedding
t0 = time.time()
X_lle_reduced = LocallyLinearEmbedding(n_components=2, random_state=42).fit_transform(image_vectors_check)
t1 = time.time()
print("LLE took {:.1f}s.".format(t1 - t0))
plot_digits(X_lle_reduced, y)
plt.show()
from sklearn.pipeline import Pipeline
pca_lle = Pipeline([
("pca", PCA(n_components=0.95, random_state=42)),
("lle", LocallyLinearEmbedding(n_components=2, random_state=42)),
])
t0 = time.time()
X_pca_lle_reduced = pca_lle.fit_transform(image_vectors_check)
t1 = time.time()
print("PCA+LLE took {:.1f}s.".format(t1 - t0))
plot_digits(X_pca_lle_reduced, y)
plt.show()
from sklearn.manifold import MDS
m = 2000
t0 = time.time()
X_mds_reduced = MDS(n_components=2, random_state=42).fit_transform(image_vectors_check[:m])
t1 = time.time()
print("MDS took {:.1f}s (on just 2,000 MNIST images instead of 10,000).".format(t1 - t0))
plot_digits(X_mds_reduced, y[:m])
plt.show()
from sklearn.pipeline import Pipeline
pca_mds = Pipeline([
("pca", PCA(n_components=0.95, random_state=42)),
("mds", MDS(n_components=2, random_state=42)),
])
t0 = time.time()
X_pca_mds_reduced = pca_mds.fit_transform(image_vectors_check[:2000])
t1 = time.time()
print("PCA+MDS took {:.1f}s (on 2,000 MNIST images).".format(t1 - t0))
plot_digits(X_pca_mds_reduced, y[:2000])
plt.show()
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
t0 = time.time()
X_lda_reduced = LinearDiscriminantAnalysis(n_components=2).fit_transform(image_vectors_check, y)
t1 = time.time()
print("LDA took {:.1f}s.".format(t1 - t0))
plot_digits(X_lda_reduced, y, figsize=(12,12))
plt.show()
from sklearn.manifold import TSNE
t0 = time.time()
X_tsne_reduced = TSNE(n_components=2, random_state=42).fit_transform(image_vectors_check)
t1 = time.time()
print("t-SNE took {:.1f}s.".format(t1 - t0))
plot_digits(X_tsne_reduced, y)
plt.show()
pca_tsne = Pipeline([
("pca", PCA(n_components=0.95, random_state=42)),
("tsne", TSNE(n_components=2, random_state=42)),
])
t0 = time.time()
X_pca_tsne_reduced = pca_tsne.fit_transform(image_vectors_check)
t1 = time.time()
print("PCA+t-SNE took {:.1f}s.".format(t1 - t0))
plot_digits(X_pca_tsne_reduced, y)
plt.show()
#Nearest Neighbours
#Douglas Duhaime
#https://github.com/YaleDHLab/pix-plot
from annoy import AnnoyIndex
from scipy import spatial
from nltk import ngrams
import random, json, glob, os, codecs, random
import numpy as np
# data structures
file_index_to_file_name = {}
file_index_to_file_vector = {}
chart_image_positions = {}
# config
dims = 2048
n_nearest_neighbors = 30
trees = 10000
infiles = glob.glob('/Users/anthonysutton/ml2/image_similar/image_vectors_DH/*.npz')
# build ann index
t = AnnoyIndex(dims)
for file_index, i in enumerate(infiles):
file_vector = np.loadtxt(i)
file_name = os.path.basename(i).split('.')[0]
file_index_to_file_name[file_index] = file_name
file_index_to_file_vector[file_index] = file_vector
t.add_item(file_index, file_vector)
t.build(trees)
# create a nearest neighbors json file for each input
if not os.path.exists('nearest_neighbors'):
os.makedirs('nearest_neighbors')
for i in file_index_to_file_name.keys():
print('Filename=' + str(i) + 'jpg')
master_file_name = file_index_to_file_name[i]
master_vector = file_index_to_file_vector[i]
named_nearest_neighbors = []
nearest_neighbors = t.get_nns_by_item(i, n_nearest_neighbors)
for j in nearest_neighbors:
neighbor_file_name = file_index_to_file_name[j]
neighbor_file_vector = file_index_to_file_vector[j]
similarity = 1 - spatial.distance.cosine(master_vector, neighbor_file_vector)
rounded_similarity = int((similarity * 10000)) / 10000.0
print('Nearest Neigbour: ' + str(neighbor_file_name) + '.jpg')
print("Similarity Measure=" + str(rounded_similarity))
named_nearest_neighbors.append({
'filename': neighbor_file_name,
'similarity': rounded_similarity
})
with open('nearest_neighbors/' + master_file_name + '3.json', 'w') as out:
json.dump(named_nearest_neighbors, out)
import tensorflow as tf
import matplotlib.pyplot as plt
# A sample image
image = plt.imread('/Users/anthonysutton/ml2/Feature_Extract/test2.png')
#image = plt.imread('/Users/anthonysutton/ml2/Feature_Extract/test.png')
fig, ax = plt.subplots()
ax.imshow(image)
#ax.axis('off') # clear x- and y-axes
# A sample image from our CNN Classification Task
image = plt.imread('/Users/anthonysutton/ml2/tensorflow-for-poets-2/tf_files/ldd_newbuild_images_arch/strong_image/location-1185-270.jpg')
fig, ax = plt.subplots()
ax.imshow(image)
#ax.axis('off') # clear x- and y-axes
image_file = '/Users/anthonysutton/ml2/tensorflow-for-poets-2/tf_files/ldd_newbuild_images_arch/strong_image/location-1185-270.jpg'
image_string = tf.gfile.FastGFile(image_file, 'rb').read()
#ksize_rows = 299
#ksize_cols = 299
#strides_rows = 128
#strides_cols = 128
ksize_rows = 100
ksize_cols = 200
strides_rows = 128
strides_cols = 128
sess = tf.InteractiveSession()
image = tf.image.decode_image(image_string, channels=3)
# The size of sliding window
ksizes = [1, ksize_rows, ksize_cols, 1]
# How far the centers of 2 consecutive patches are in the image
strides = [1, strides_rows, strides_cols, 1]
# The document is unclear. However, an intuitive example posted on StackOverflow illustrate its behaviour clearly.
# http://stackoverflow.com/questions/40731433/understanding-tf-extract-image-patches-for-extracting-patches-from-an-image
rates = [1, 1, 1, 1] # sample pixel consecutively
# padding algorithm to used
padding='VALID' # or 'SAME'
image = tf.expand_dims(image, 0)
image_patches = tf.extract_image_patches(image, ksizes, strides, rates, padding)
# print image shape of image patches
print(sess.run(tf.shape(image_patches)))
# image_patches is 4 dimension array, you can use tf.squeeze to squeeze it, e.g.
#image_patches = tf.squeeze(image_patches)
# retrieve the 1st patches
patch1 = image_patches[0,2,2,]
patch2 = image_patches[0,0,3,]
patch3 = image_patches[0,0,0,]
patch4 = image_patches[0,0,1,]
patch5 = image_patches[0,1,1,]
patch6 = image_patches[1,1,1,]
patch7 = image_patches[1,1,2,]
patch8 = image_patches[1,2,2,]
patch9 = image_patches[2,2,2,]
patch10 = image_patches[2,2,3,]
patch11 = image_patches[2,3,3,]
patch12 = image_patches[3,3,3,]
# reshape
patch1 = tf.reshape(patch1, [ksize_rows, ksize_cols, 3])
patch2 = tf.reshape(patch2, [ksize_rows, ksize_cols, 3])
patch3 = tf.reshape(patch3, [ksize_rows, ksize_cols, 3])
patch4 = tf.reshape(patch4, [ksize_rows, ksize_cols, 3])
patch5 = tf.reshape(patch5, [ksize_rows, ksize_cols, 3])
#patch6 = tf.reshape(patch6, [ksize_rows, ksize_cols, 3])
#patch7 = tf.reshape(patch7, [ksize_rows, ksize_cols, 3])
#patch8 = tf.reshape(patch8, [ksize_rows, ksize_cols, 3])
#patch9 = tf.reshape(patch9, [ksize_rows, ksize_cols, 3])
#patch10 = tf.reshape(patch10, [ksize_rows, ksize_cols, 3])
#patch11 = tf.reshape(patch11, [ksize_rows, ksize_cols, 3])
#patch12 = tf.reshape(patch12, [ksize_rows, ksize_cols, 3])
# visualize image
#import matplotlib.pyplot as plt
#plt.imshow(sess.run(patch1))
#plt.show()
#plt.imshow(sess.run(patch2))
#plt.show()
plt.imshow(sess.run(patch3))
plt.show()
plt.imshow(sess.run(patch4))
plt.show()
plt.imshow(sess.run(patch5))
plt.show()
#plt.imshow(sess.run(patch6))
#plt.show()
#plt.imshow(sess.run(patch7))
#plt.show()
#plt.imshow(sess.run(patch8))
#plt.show()
#plt.imshow(sess.run(patch9))
#plt.show()
#plt.imshow(sess.run(patch10))
#plt.show()
#plt.imshow(sess.run(patch11))
#plt.show()
#plt.imshow(sess.run(patch12))
#plt.show()
# close session
sess.close()
#TO DO:
print(__doc__)
from time import time
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import offsetbox
from sklearn import (manifold, datasets, decomposition, ensemble,
discriminant_analysis, random_projection, neighbors)
digits = datasets.load_digits(n_class=6)
X = digits.data
y = digits.target
n_samples, n_features = X.shape
n_neighbors = 30
# ----------------------------------------------------------------------
# Scale and visualize the embedding vectors
def plot_embedding(X, title=None):
x_min, x_max = np.min(X, 0), np.max(X, 0)
X = (X - x_min) / (x_max - x_min)
plt.figure()
ax = plt.subplot(111)
for i in range(X.shape[0]):
plt.text(X[i, 0], X[i, 1], str(y[i]),
color=plt.cm.Set1(y[i] / 10.),
fontdict={'weight': 'bold', 'size': 9})
if hasattr(offsetbox, 'AnnotationBbox'):
# only print thumbnails with matplotlib > 1.0
shown_images = np.array([[1., 1.]]) # just something big
for i in range(X.shape[0]):
dist = np.sum((X[i] - shown_images) ** 2, 1)
if np.min(dist) < 4e-3:
# don't show points that are too close
continue
shown_images = np.r_[shown_images, [X[i]]]
imagebox = offsetbox.AnnotationBbox(
offsetbox.OffsetImage(digits.images[i], cmap=plt.cm.gray_r),
X[i])
ax.add_artist(imagebox)
plt.xticks([]), plt.yticks([])
if title is not None:
plt.title(title)
# ----------------------------------------------------------------------
# Plot images of the digits
n_img_per_row = 20
img = np.zeros((10 * n_img_per_row, 10 * n_img_per_row))
for i in range(n_img_per_row):
ix = 10 * i + 1
for j in range(n_img_per_row):
iy = 10 * j + 1
img[ix:ix + 8, iy:iy + 8] = X[i * n_img_per_row + j].reshape((8, 8))
plt.imshow(img, cmap=plt.cm.binary)
plt.xticks([])
plt.yticks([])
plt.title('A selection from the 64-dimensional digits dataset')
# ----------------------------------------------------------------------
# Random 2D projection using a random unitary matrix
print("Computing random projection")
rp = random_projection.SparseRandomProjection(n_components=2, random_state=42)
X_projected = rp.fit_transform(X)
plot_embedding(X_projected, "Random Projection of the digits")
#----------------------------------------------------------------------
# Projection on to the first 2 principal components
print("Computing PCA projection")
t0 = time()
X_pca = decomposition.TruncatedSVD(n_components=2).fit_transform(X)
plot_embedding(X_pca,
"Principal Components projection of the digits (time %.2fs)" %
(time() - t0))
# ----------------------------------------------------------------------
# Projection on to the first 2 linear discriminant components
print("Computing Linear Discriminant Analysis projection")
X2 = X.copy()
X2.flat[::X.shape[1] + 1] += 0.01 # Make X invertible
t0 = time()
X_lda = discriminant_analysis.LinearDiscriminantAnalysis(n_components=2).fit_transform(X2, y)
plot_embedding(X_lda,
"Linear Discriminant projection of the digits (time %.2fs)" %
(time() - t0))
# ----------------------------------------------------------------------
# Isomap projection of the digits dataset
print("Computing Isomap projection")
t0 = time()
X_iso = manifold.Isomap(n_neighbors, n_components=2).fit_transform(X)
print("Done.")
plot_embedding(X_iso,
"Isomap projection of the digits (time %.2fs)" %
(time() - t0))
# ----------------------------------------------------------------------
# Locally linear embedding of the digits dataset
print("Computing LLE embedding")
clf = manifold.LocallyLinearEmbedding(n_neighbors, n_components=2,
method='standard')
t0 = time()
X_lle = clf.fit_transform(X)
print("Done. Reconstruction error: %g" % clf.reconstruction_error_)
plot_embedding(X_lle,
"Locally Linear Embedding of the digits (time %.2fs)" %
(time() - t0))
# ----------------------------------------------------------------------
# Modified Locally linear embedding of the digits dataset
print("Computing modified LLE embedding")
clf = manifold.LocallyLinearEmbedding(n_neighbors, n_components=2,
method='modified')
t0 = time()
X_mlle = clf.fit_transform(X)
print("Done. Reconstruction error: %g" % clf.reconstruction_error_)
plot_embedding(X_mlle,
"Modified Locally Linear Embedding of the digits (time %.2fs)" %
(time() - t0))
# ----------------------------------------------------------------------
# HLLE embedding of the digits dataset
print("Computing Hessian LLE embedding")
clf = manifold.LocallyLinearEmbedding(n_neighbors, n_components=2,
method='hessian')
t0 = time()
X_hlle = clf.fit_transform(X)
print("Done. Reconstruction error: %g" % clf.reconstruction_error_)
plot_embedding(X_hlle,
"Hessian Locally Linear Embedding of the digits (time %.2fs)" %
(time() - t0))
# ----------------------------------------------------------------------
# LTSA embedding of the digits dataset
print("Computing LTSA embedding")
clf = manifold.LocallyLinearEmbedding(n_neighbors, n_components=2,
method='ltsa')
t0 = time()
X_ltsa = clf.fit_transform(X)
print("Done. Reconstruction error: %g" % clf.reconstruction_error_)
plot_embedding(X_ltsa,
"Local Tangent Space Alignment of the digits (time %.2fs)" %
(time() - t0))
# ----------------------------------------------------------------------
# MDS embedding of the digits dataset
print("Computing MDS embedding")
clf = manifold.MDS(n_components=2, n_init=1, max_iter=100)
t0 = time()
X_mds = clf.fit_transform(X)
print("Done. Stress: %f" % clf.stress_)
plot_embedding(X_mds,
"MDS embedding of the digits (time %.2fs)" %
(time() - t0))
# ----------------------------------------------------------------------
# Random Trees embedding of the digits dataset
print("Computing Totally Random Trees embedding")
hasher = ensemble.RandomTreesEmbedding(n_estimators=200, random_state=0,
max_depth=5)
t0 = time()
X_transformed = hasher.fit_transform(X)
pca = decomposition.TruncatedSVD(n_components=2)
X_reduced = pca.fit_transform(X_transformed)
plot_embedding(X_reduced,
"Random forest embedding of the digits (time %.2fs)" %
(time() - t0))
# ----------------------------------------------------------------------
# Spectral embedding of the digits dataset
print("Computing Spectral embedding")
embedder = manifold.SpectralEmbedding(n_components=2, random_state=0,
eigen_solver="arpack")
t0 = time()
X_se = embedder.fit_transform(X)
plot_embedding(X_se,
"Spectral embedding of the digits (time %.2fs)" %
(time() - t0))
# ----------------------------------------------------------------------
# t-SNE embedding of the digits dataset
print("Computing t-SNE embedding")
tsne = manifold.TSNE(n_components=2, init='pca', random_state=0)
t0 = time()
X_tsne = tsne.fit_transform(X)
plot_embedding(X_tsne,
"t-SNE embedding of the digits (time %.2fs)" %
(time() - t0))
# ----------------------------------------------------------------------
# NCA projection of the digits dataset
print("Computing NCA projection")
nca = neighbors.NeighborhoodComponentsAnalysis(n_components=2, random_state=0)
t0 = time()
X_nca = nca.fit_transform(X, y)
plot_embedding(X_nca,
"NCA embedding of the digits (time %.2fs)" %
(time() - t0))
plt.show()